import { LitElement, html, css } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';

/**
 * DatePicker日期选择器组件
 * @element zss-date-picker
 */
@customElement('zss-date-picker')
export class ZssDatePicker extends LitElement {
  static styles = css`
    :host {
      display: inline-block;
      position: relative;
    }

    .date-picker {
      position: relative;
      display: inline-block;
    }

    .date-picker__input {
      width: 100%;
      border: 1px solid var(--zss-border-color);
      border-radius: var(--zss-border-radius-base);
      padding: 8px 12px;
      font-size: var(--zss-font-size-base);
      background-color: var(--zss-bg-color);
      color: var(--zss-text-color-regular);
      outline: none;
      transition: border-color 0.2s;
    }

    .date-picker__input:hover {
      border-color: var(--zss-border-color-light);
    }

    .date-picker__input:focus {
      border-color: var(--zss-color-primary);
      box-shadow: 0 0 0 2px var(--zss-color-primary-light-8);
    }

    .date-picker__input.disabled {
      background-color: var(--zss-fill-color-light);
      border-color: var(--zss-border-color-light);
      color: var(--zss-text-color-disabled);
      cursor: not-allowed;
    }

    .date-picker__panel {
      position: absolute;
      top: 100%;
      left: 0;
      z-index: 2000;
      background: var(--zss-bg-color);
      border: 1px solid var(--zss-border-color-lighter);
      border-radius: var(--zss-border-radius-base);
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      margin-top: 4px;
      min-width: 240px;
    }

    .date-picker__header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px;
      border-bottom: 1px solid var(--zss-border-color-lighter);
    }

    .date-picker__prev-btn,
    .date-picker__next-btn {
      background: none;
      border: none;
      cursor: pointer;
      padding: 4px;
      color: var(--zss-text-color-regular);
    }

    .date-picker__prev-btn:hover,
    .date-picker__next-btn:hover {
      color: var(--zss-color-primary);
    }

    .date-picker__title {
      font-weight: var(--zss-font-weight-primary);
      color: var(--zss-text-color-primary);
    }

    .date-picker__body {
      padding: 12px;
    }

    .date-picker__week-days {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      text-align: center;
      margin-bottom: 8px;
    }

    .date-picker__week-day {
      font-size: var(--zss-font-size-small);
      color: var(--zss-text-color-secondary);
      padding: 4px;
    }

    .date-picker__dates {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 4px;
    }

    .date-picker__date {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 32px;
      border-radius: var(--zss-border-radius-base);
      cursor: pointer;
      font-size: var(--zss-font-size-small);
      color: var(--zss-text-color-regular);
    }

    .date-picker__date:hover {
      background-color: var(--zss-fill-color-light);
    }

    .date-picker__date.today {
      color: var(--zss-color-primary);
      font-weight: var(--zss-font-weight-primary);
    }

    .date-picker__date.selected {
      background-color: var(--zss-color-primary);
      color: var(--zss-color-white);
    }

    .date-picker__date.disabled {
      color: var(--zss-text-color-disabled);
      cursor: not-allowed;
    }

    .date-picker__date.disabled:hover {
      background-color: transparent;
    }

    .date-picker__date.other-month {
      color: var(--zss-text-color-placeholder);
    }
  `;

  /**
   * 绑定值
   * @attr value
   */
  @property({ type: String })
  value = '';

  /**
   * 占位符
   * @attr placeholder
   */
  @property({ type: String })
  placeholder = '请选择日期';

  /**
   * 是否禁用
   * @attr disabled
   */
  @property({ type: Boolean })
  disabled = false;

  /**
   * 是否可清空
   * @attr clearable
   */
  @property({ type: Boolean })
  clearable = false;

  /**
   * 日期格式
   * @attr format
   */
  @property({ type: String })
  format = 'YYYY-MM-DD';

  /**
   * 选择器类型
   * @attr type
   */
  @property({ type: String })
  type: 'date' | 'datetime' | 'daterange' = 'date';

  @state()
  private showPanel = false;

  @state()
  private currentDate = new Date();

  @state()
  private selectedDate: Date | null = null;

  private getDaysInMonth(year: number, month: number) {
    return new Date(year, month + 1, 0).getDate();
  }

  private getFirstDayOfMonth(year: number, month: number) {
    return new Date(year, month, 1).getDay();
  }

  private formatDate(date: Date, format: string) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return format
      .replace('YYYY', year.toString())
      .replace('MM', month)
      .replace('DD', day);
  }

  private parseDate(dateString: string) {
    if (!dateString) return null;
    
    const parts = dateString.split('-');
    if (parts.length === 3) {
      return new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]));
    }
    return null;
  }

  private togglePanel() {
    if (this.disabled) return;
    this.showPanel = !this.showPanel;
  }

  private handleInputClick(e: Event) {
    e.stopPropagation();
    this.togglePanel();
  }

  private handleDocumentClick = () => {
    this.showPanel = false;
  };

  connectedCallback() {
    super.connectedCallback();
    document.addEventListener('click', this.handleDocumentClick);
    
    if (this.value) {
      this.selectedDate = this.parseDate(this.value);
      if (this.selectedDate) {
        this.currentDate = new Date(this.selectedDate);
      }
    }
  }

  disconnectedCallback() {
    document.removeEventListener('click', this.handleDocumentClick);
    super.disconnectedCallback();
  }

  private handleDateSelect(date: Date) {
    this.selectedDate = date;
    this.value = this.formatDate(date, this.format);
    this.showPanel = false;
    
    this.dispatchEvent(new CustomEvent('change', { 
      detail: { value: this.value, date: this.selectedDate } 
    }));
  }

  private handlePrevMonth() {
    this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() - 1, 1);
  }

  private handleNextMonth() {
    this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() + 1, 1);
  }

  private clearValue() {
    this.value = '';
    this.selectedDate = null;
    this.dispatchEvent(new CustomEvent('change', { detail: { value: '', date: null } }));
  }

  private renderCalendar() {
    const year = this.currentDate.getFullYear();
    const month = this.currentDate.getMonth();
    const daysInMonth = this.getDaysInMonth(year, month);
    const firstDay = this.getFirstDayOfMonth(year, month);
    
    const today = new Date();
    const dates = [];
    
    // 上个月的日期
    const prevMonthDays = this.getDaysInMonth(year, month - 1);
    for (let i = firstDay - 1; i >= 0; i--) {
      dates.push({
        date: new Date(year, month - 1, prevMonthDays - i),
        isCurrentMonth: false
      });
    }
    
    // 当前月的日期
    for (let i = 1; i <= daysInMonth; i++) {
      dates.push({
        date: new Date(year, month, i),
        isCurrentMonth: true
      });
    }
    
    // 下个月的日期
    const totalCells = 42; // 6行 * 7列
    const remainingCells = totalCells - dates.length;
    for (let i = 1; i <= remainingCells; i++) {
      dates.push({
        date: new Date(year, month + 1, i),
        isCurrentMonth: false
      });
    }
    
    return html`
      <div class="date-picker__panel" @click=${(e: Event) => e.stopPropagation()}>
        <div class="date-picker__header">
          <button class="date-picker__prev-btn" @click=${this.handlePrevMonth}>‹</button>
          <span class="date-picker__title">
            ${year}年${month + 1}月
          </span>
          <button class="date-picker__next-btn" @click=${this.handleNextMonth}>›</button>
        </div>
        
        <div class="date-picker__body">
          <div class="date-picker__week-days">
            ${['日', '一', '二', '三', '四', '五', '六'].map(day => html`
              <div class="date-picker__week-day">${day}</div>
            `)}
          </div>
          
          <div class="date-picker__dates">
            ${dates.map(item => {
              const isToday = item.date.toDateString() === today.toDateString();
              const isSelected = this.selectedDate && item.date.toDateString() === this.selectedDate.toDateString();
              
              return html`
                <div 
                  class="date-picker__date 
                    ${isToday ? 'today' : ''} 
                    ${isSelected ? 'selected' : ''} 
                    ${!item.isCurrentMonth ? 'other-month' : ''}"
                  @click=${() => this.handleDateSelect(item.date)}
                >
                  ${item.date.getDate()}
                </div>
              `;
            })}
          </div>
        </div>
      </div>
    `;
  }

  render() {
    return html`
      <div class="date-picker">
        <input
          class="date-picker__input ${this.disabled ? 'disabled' : ''}"
          .value=${this.value}
          .placeholder=${this.placeholder}
          ?disabled=${this.disabled}
          @click=${this.handleInputClick}
          readonly
        />
        
        ${this.clearable && this.value ? html`
          <span @click=${this.clearValue} style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); cursor: pointer;">
            ×
          </span>
        ` : ''}
        
        ${this.showPanel ? this.renderCalendar() : ''}
      </div>
    `;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'zss-date-picker': ZssDatePicker;
  }
}